import { College } from '../models/College.js';
import { Student } from '../models/Student.js';
import { Class } from '../models/Class.js';
import { Teacher } from '../models/Teacher.js';

const collegeModel = new College();
const studentModel = new Student();
const classModel = new Class();
const teacherModel = new Teacher();

export class CollegeController {
  // 获取学院列表
  async getColleges(req, res) {
    try {
      console.log('获取学院列表，查询参数:', req.query);
      
      const colleges = collegeModel.findAll();
      
      // 处理分页
      const page = parseInt(req.query.page) || 1;
      const pageSize = parseInt(req.query.pageSize) || 10;
      const startIndex = (page - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      
      // 应用搜索过滤
      let filteredColleges = [...colleges];
      
      // 关键词搜索
      if (req.query.keyword) {
        const keyword = req.query.keyword.toLowerCase();
        filteredColleges = filteredColleges.filter(college => 
          college.name.toLowerCase().includes(keyword) ||
          college.dean.toLowerCase().includes(keyword) ||
          (college.description && college.description.toLowerCase().includes(keyword)) ||
          college.email.toLowerCase().includes(keyword) ||
          college.address.toLowerCase().includes(keyword)
        );
      }
      
      // 分页
      const paginatedColleges = filteredColleges.slice(startIndex, endIndex);
      
      // 关联班级和学生数据
      const classes = classModel.findAll();
      const students = studentModel.findAll();
      const teachers = teacherModel.findAll();
      
      const collegesWithDetails = paginatedColleges.map(college => {
        const collegeClasses = classes.filter(cls => cls.department === college.name);
        const collegeStudents = students.filter(student => student.college === college.name);
        const collegeTeachers = teachers.filter(teacher => teacher.department === college.name);
        
        return {
          ...college,
          actualStudentCount: collegeStudents.length,
          actualClassCount: collegeClasses.length,
          actualTeacherCount: collegeTeachers.length,
          classes: collegeClasses,
          students: collegeStudents,
          teachers: collegeTeachers
        };
      });
      
      // 构建响应
      const response = {
        success: true,
        data: collegesWithDetails,
        pagination: {
          current: page,
          pageSize: pageSize,
          total: filteredColleges.length,
          totalPages: Math.ceil(filteredColleges.length / pageSize)
        }
      };
      
      console.log('返回学院数据:', {
        dataCount: collegesWithDetails.length,
        total: filteredColleges.length,
        pagination: response.pagination
      });
      
      res.json(response);
    } catch (error) {
      console.error('获取学院列表失败:', error);
      res.status(500).json({ 
        success: false,
        error: '获取失败' 
      });
    }
  }

  // 获取学院选项数据
  async getCollegeOptions(req, res) {
    try {
      const colleges = collegeModel.findAll();
      
      const collegeOptions = colleges.map(college => ({
        value: college.name,
        label: college.name
      }));
      
      res.json({
        success: true,
        data: collegeOptions
      });
    } catch (error) {
      console.error('获取学院选项失败:', error);
      res.status(500).json({ 
        success: false,
        error: '获取失败' 
      });
    }
  }

  // 获取学院统计信息
  async getCollegeStats(req, res) {
    try {
      const colleges = collegeModel.findAll();
      const students = studentModel.findAll();
      const classes = classModel.findAll();
      const teachers = teacherModel.findAll();
      
      const totalColleges = colleges.length;
      let totalStudents = 0;
      let totalClasses = 0;
      let totalTeachers = 0;
      
      const collegeStats = colleges.map(college => {
        const collegeStudents = students.filter(student => student.college === college.name);
        const collegeClasses = classes.filter(cls => cls.department === college.name);
        const collegeTeachers = teachers.filter(teacher => teacher.department === college.name);
        
        totalStudents += collegeStudents.length;
        totalClasses += collegeClasses.length;
        totalTeachers += collegeTeachers.length;
        
        return {
          name: college.name,
          studentCount: collegeStudents.length,
          classCount: collegeClasses.length,
          teacherCount: collegeTeachers.length,
          dean: college.dean,
          phone: college.phone
        };
      });
      
      res.json({
        success: true,
        data: {
          totalColleges,
          totalStudents,
          totalClasses,
          totalTeachers,
          averageStudentsPerCollege: totalColleges > 0 ? Math.round(totalStudents / totalColleges) : 0,
          averageClassesPerCollege: totalColleges > 0 ? Math.round(totalClasses / totalColleges) : 0,
          collegeStats
        }
      });
    } catch (error) {
      console.error('获取学院统计失败:', error);
      res.status(500).json({ 
        success: false,
        error: '获取失败' 
      });
    }
  }

  // 创建学院
  async createCollege(req, res) {
    try {
      const {
        name,
        totalStudents,
        totalClasses,
        totalTeachers,
        totalCounselors,
        dean,
        phone,
        email,
        address,
        description,
        status
      } = req.body;
      
      console.log('创建学院:', { name, dean });

      if (!name) {
        return res.status(400).json({ 
          success: false,
          error: '学院名称为必填字段' 
        });
      }

      const colleges = collegeModel.findAll();
      
      // 检查学院名称是否已存在
      if (colleges.find(c => c.name === name)) {
        return res.status(400).json({ 
          success: false,
          error: '学院名称已存在' 
        });
      }

      const newCollege = {
        name,
        totalStudents: totalStudents || 0,
        totalClasses: totalClasses || 0,
        totalTeachers: totalTeachers || 0,
        totalCounselors: totalCounselors || 0,
        dean: dean || '',
        phone: phone || '',
        email: email || '',
        address: address || '',
        description: description || '',
        status: status || 'active'
      };

      const createdCollege = collegeModel.create(newCollege);
      
      if (createdCollege) {
        console.log('创建学院成功:', createdCollege);
        res.status(201).json({
          success: true,
          data: createdCollege
        });
      } else {
        res.status(500).json({ 
          success: false,
          error: '保存失败' 
        });
      }
    } catch (error) {
      console.error('创建学院失败:', error);
      res.status(500).json({ 
        success: false,
        error: '创建失败' 
      });
    }
  }

  // 更新学院
  async updateCollege(req, res) {
    try {
      const { id } = req.params;
      const {
        name,
        totalStudents,
        totalClasses,
        totalTeachers,
        totalCounselors,
        dean,
        phone,
        email,
        address,
        description,
        status
      } = req.body;
      
      console.log('更新学院:', id, { name, dean });

      const colleges = collegeModel.findAll();
      
      // 检查学院名称是否被其他学院使用
      if (colleges.find(c => c.name === name && c.id !== parseInt(id))) {
        return res.status(400).json({ 
          success: false,
          error: '学院名称已被其他学院使用' 
        });
      }

      const updatedCollege = collegeModel.update(id, {
        name,
        totalStudents: totalStudents || 0,
        totalClasses: totalClasses || 0,
        totalTeachers: totalTeachers || 0,
        totalCounselors: totalCounselors || 0,
        dean: dean || '',
        phone: phone || '',
        email: email || '',
        address: address || '',
        description: description || '',
        status: status || 'active'
      });

      if (updatedCollege) {
        console.log('更新学院成功:', updatedCollege);
        res.json({
          success: true,
          data: updatedCollege
        });
      } else {
        res.status(404).json({ 
          success: false,
          error: '学院不存在' 
        });
      }
    } catch (error) {
      console.error('更新学院失败:', error);
      res.status(500).json({ 
        success: false,
        error: '更新失败' 
      });
    }
  }

  // 删除学院
  async deleteCollege(req, res) {
    try {
      const { id } = req.params;
      console.log('删除学院:', id);
      
      const colleges = collegeModel.findAll();
      const classes = classModel.findAll();
      const students = studentModel.findAll();
      const teachers = teacherModel.findAll();
      
      // 检查是否有班级、学生或老师关联此学院
      const college = colleges.find(c => c.id === parseInt(id));
      if (college) {
        const relatedClasses = classes.filter(cls => cls.department === college.name);
        const relatedStudents = students.filter(student => student.college === college.name);
        const relatedTeachers = teachers.filter(teacher => teacher.department === college.name);
        
        if (relatedClasses.length > 0 || relatedStudents.length > 0 || relatedTeachers.length > 0) {
          return res.status(400).json({ 
            success: false,
            error: `无法删除，该学院下还有 ${relatedClasses.length} 个班级、${relatedStudents.length} 名学生和 ${relatedTeachers.length} 名老师` 
          });
        }
      }

      const success = collegeModel.delete(id);
      
      if (success) {
        console.log('删除学院成功');
        res.json({ 
          success: true,
          message: '删除成功' 
        });
      } else {
        res.status(404).json({ 
          success: false,
          error: '学院不存在' 
        });
      }
    } catch (error) {
      console.error('删除学院失败:', error);
      res.status(500).json({ 
        success: false,
        error: '删除失败' 
      });
    }
  }

  // 获取学院详情
  async getCollegeDetail(req, res) {
    try {
      const { id } = req.params;
      console.log('获取学院详情:', id);
      
      const college = collegeModel.findById(id);
      if (!college) {
        return res.status(404).json({ 
          success: false,
          error: '学院不存在' 
        });
      }

      // 关联数据
      const classes = classModel.findAll();
      const students = studentModel.findAll();
      const teachers = teacherModel.findAll();
      
      const collegeClasses = classes.filter(cls => cls.department === college.name);
      const collegeStudents = students.filter(student => student.college === college.name);
      const collegeTeachers = teachers.filter(teacher => teacher.department === college.name);

      const collegeDetail = {
        ...college,
        actualStudentCount: collegeStudents.length,
        actualClassCount: collegeClasses.length,
        actualTeacherCount: collegeTeachers.length,
        actualCounselorCount: 0, // 可以根据需要计算辅导员数量
        classes: collegeClasses,
        students: collegeStudents.slice(0, 10), // 只返回前10名学生
        teachers: collegeTeachers.slice(0, 10)  // 只返回前10名老师
      };

      res.json({
        success: true,
        data: collegeDetail
      });
    } catch (error) {
      console.error('获取学院详情失败:', error);
      res.status(500).json({ 
        success: false,
        error: '获取失败' 
      });
    }
  }
}